package api.apiservice.apiopenplat.controller;
import api.apiservice.apiopenplat.Utils.verify.verifyAction;
import api.apiservice.apiopenplat.Utils.verify.verifyApier;
import api.apiservice.apiopenplat.entity.ApiProvider;
import api.apiservice.apiopenplat.mapper.ApiInfoMapper;
import api.apiservice.apiopenplat.pojo.condition.ApiInfoIndex;
import api.apiservice.apiopenplat.service.ApiProviderService;
import cn.hutool.http.HttpResponse;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import api.apiservice.apiopenplat.Utils.HttpUtils;
import api.apiservice.apiopenplat.common.unifyDataForm.Result;
import api.apiservice.apiopenplat.common.unifyDataForm.ResultVo;
import api.apiservice.apiopenplat.entity.ApiInfo;
import api.apiservice.apiopenplat.pojo.access.accessPromission;
import api.apiservice.apiopenplat.pojo.add.ApiAdd;
import api.apiservice.apiopenplat.pojo.update.ApiUpdate;
import api.apiservice.apiopenplat.service.IApiInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Tangshen
 * @since 2022-11-11
 */
@RestController
@Api(tags = "API控制器")
@RequestMapping("/system/apiInfo")
@CrossOrigin
public class ApiInfoController {

    @DubboReference
    private IApiInfoService apiInfoService;

    @Autowired
    private ApiProviderService apiProviderService;

    @Autowired
    private RedisTemplate redisTemplate;


    private static long currentTime = System.currentTimeMillis();

    private static long useCount = 0;

    private static String verify ;


    @ApiOperation(value = "API信息总览")
    @GetMapping("PageApiInfo")
    public Result<List<ApiInfoIndex>> PageApiInfo(){
        List<ApiInfoIndex> list = apiInfoService.pageApiList();
        return Result.success(list);
    }


    @ApiOperation(value = "API上线")
    @GetMapping("upLineApi/{aId}")
    public Result UpLineApi(@PathVariable("aId") Long aId){
        ApiInfo apiInfo = apiInfoService.searchApiById(aId);
        Long pId = apiInfo.getAProvider();
        ApiProvider apiProvider = apiProviderService.searchProviderById(pId);
        String appfront = apiProvider.getPip()+":"  +apiProvider.getPport();
        verifyAction verifyAction = new verifyApier(appfront,apiInfo.getAUri(),apiInfo.getAMethod());
        boolean verifyResult = verifyAction.verifyApiAction();
        if (verifyResult){
            ApiUpdate update = new ApiUpdate();
            update.setAId(aId);
            update.setIsUsedAble(1);
            apiInfoService.updateApiInfoById(update);
        }else{
            return Result.error(ResultVo.ERROR_URI);
        }
        return  Result.error(ResultVo.ERROR_UNKOWN);
    }


    /**
     * 添加API Controller
     * */
    @ApiOperation(value = "添加API")
    @PostMapping("InsertApi")
    public Result InsertApiInfo(@RequestBody ApiInfo apiAdd){
        boolean isInsert = apiInfoService.saveApiInfo(apiAdd);
        return isInsert ? Result.success() : Result.error(ResultVo.ERROR_UNKOWN);
    }

    /*
    *   API下线
    *
    * */
    @ApiOperation(value = "API下线")
    @GetMapping("downLine/{aid}")
    public Result downLineApi(@PathVariable Long aid){
        //TODO 查看这个用户是否拥有该权限
        ApiUpdate update = new ApiUpdate();
        update.setAId(aid);
        update.setIsUsedAble(0);
        boolean result = apiInfoService.updateApiInfoById(update);
        if (result){
            return Result.success("删除成功！");
        }
        return Result.error(ResultVo.ERROR_UNKOWN);
    }


    /**
     *
     * API信息更改 Controller
     *
     * */
    @PostMapping("UpdateApi")
    @ApiOperation(value = "更新API")
    public Result UpdateApiInfo(@RequestBody ApiUpdate apiUpdate){
       boolean isUpdate =  apiInfoService.updateApiInfoById(apiUpdate);
       return isUpdate ? Result.success() : Result.error(ResultVo.ERROR_UNKOWN);
    }

    @GetMapping("selectAById/{id}")
    @ApiOperation(value = "查询单个API")
    public Result   selectAById(@PathVariable("id")Long id){
        ApiInfo apiInfo = apiInfoService.searchApiById(id);
        return Result.success(apiInfo);
    }

    /*
    *
    * 删除API Controller
    *
    * */
    @PostMapping("DelApi")
    @ApiOperation(value = "删除API(批量)")
    public Result delApiInfo(List<Long> idList){
        boolean isDel = apiInfoService.delApiInfo(idList);
        return isDel ? Result.success() : Result.error(ResultVo.ERROR_UNKOWN);
    }






    /*
    *
    * API发布
    *
    * */
    @PostMapping("invokeApi")
    @ApiOperation(value = "在线调用API")
    public Result OnlineApi(Long requestId, @RequestBody accessPromission permission, HttpServletResponse response){
        ApiInfo existApi = apiInfoService.isExistApi(requestId);
        if (existApi != null){
            //useCount为0 ，代表这是第一次调用
            if (useCount == 0){
                currentTime = System.currentTimeMillis();
            }
            //获取用户，根据用户找到相应的accessKey，accessSecret
            String token = (String) redisTemplate.opsForValue().get("token");
            JWT jwt = JWTUtil.parseToken(token);
            Long userId = (Long) jwt.getPayload("userId");
            //TODO 判断该用户是否被禁用
            long useTime = System.currentTimeMillis();
            HashMap<String, String> RequestMap = HttpUtils.generatorRequest(useTime-currentTime, permission.getAccessKey(), permission.getAccessSecret(), userId);
            //向请求头中存放数据，用于网关校验
            HttpUtils.appendHeader(response,RequestMap);
            String gatewayUrl = "localhost:9999/invokeApi/"+existApi.getAUri();
            HttpResponse httpResponse = HttpUtils.requestByGet(gatewayUrl, RequestMap);
            if (httpResponse.getStatus() == 200){
                System.out.println(httpResponse.body());
                return Result.success();
            }
//            if (verify != null && verify.equals(RequestMap.get("onlyId"))){
//                throw  new myException(ExceptionEnu.REQUEST_ERROR_REQUEST);
//            }
//            boolean isPass = apiInfoService.checkPermiession(RequestMap);
//
//            HashMap<String, String> apiMessage = apiInfoService.checkApiMessage(requestId);
//
//            if (isPass){
//                String result = null;
//                if (apiMessage.get("method").equals("GET")){
//                    result = HttpUtils.requestByGet(apiMessage.get("url"));
//                }
//                return Result.success(result);
//            }
//
//            useCount ++ ;
//            return Result.error(ResultVo.ERROR_APIONLINED);
        }

        return Result.error(ResultVo.ERROR_UNKOWN);
    }


    /**
     *
     *
     * API下线
     *
     * */
    @ApiOperation(value = "API下线")
    @PostMapping("offlineApi")
    public Result offlineApi(){
        return Result.success();
    }

}

